<?php

/**
 * Contrôleur de gestion des données
 */
class produit_controller extends Component
{
     // Attributs
    const byPage = 10;
    const page_identifier = 'page-';
    public $_pageTotal;

    /**
     * Constructeur
     */
    public function __construct()
    {
    }

    /**
     * Données à envoyer à la vue par défaut
     */
    public function defaut()
    {
        if (isset($_GET['param'][0])) {
            if (preg_match("/".self::page_identifier."/i", $_GET['param'][0])) {
                $p = explode(self::page_identifier, $_GET['param'][0]);
                $this->getAll($p[1]);
            }
        } else {
            $this->getAll();
        }
    }

    /**
     * Récupération de toutes les produit
     *
     * @param unsigned $page L'endroit du tableau à visualiser (pagination)
     */
    private function getAll($page = 1)
    {
        $dataTmp = Base::Load(CLASS_PRODUCT)->getAll();
        $this->_pageTotal = ceil(count($dataTmp) / self::byPage) + 1;
        $start = self::byPage * $page - self::byPage;
        $pageStart = $page - 5;

        if ($pageStart < 1) {
            $pageStart = 1;
        }

        $i = 0;
        foreach ($dataTmp as $d) {
            if ($i >= $start) {
                if ($i < $start + self::byPage) {
                    $releve = Base::Load(CLASS_RELEVE)->findBy('product', (string)$d['_id']);
                    $note = array();
                    if($releve != false){
                        foreach($releve as $r)
                            $note[] = $r['prix'];
                        $d['moyenne'] = number_format(Tools::moyenne($note), 2, ',', ' ');
                        $d['mediane'] = number_format(Tools::mediane($note), 2, ',', ' ');
                    }else {
                        $d['moyenne'] = $d['mediane'] = null;
                    }
                    $data[$i] = $d;
                } else {
                    break;
                }
            }
            $i++;
        }

        $this->_view->assign('pageTotal', $this->_pageTotal);
        $this->_view->assign('page', $page);
        $this->_view->assign('pageStart', $pageStart);
        $this->_view->assign('pageStop', $pageStart + self::byPage - 1);
        $this->_view->assign('data', $data);

        if (isset($_GET['ajax']) && $_GET['ajax']) {
            $this->_view->assign('ajax', true);
            Base::Load(CLASS_BASE)->setLayout('vide.tpl');
            $this->_view->addBlock('data', 'list.tpl');
        } else {
            $this->_view->addBlock('content', 'list.tpl');
        }
    }

    public function getAutoComplete()
    {
        $this->setContentType('text/plain');
        $query = $_GET['query'];
        $queryType = array('products');
        $data = Base::Load(CLASS_SEARCH)->MySearch($query, $queryType, true);
        exit($data);
    }
}


/* -- Fin du fichier -- */